package com.sky.ok.controller;

import com.alibaba.fastjson.JSONObject;
import com.sky.ok.common.ResponseBean;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.Map;

import static com.sky.ok.utils.MyUtils.getIp;

/**
 * 登录接口
 *
 * @author 余心乐sky
 * @create 2018-12-20 15:39
 **/
@RestController
public class Login {

  @PostMapping("/login")
    public ResponseBean login(HttpServletRequest request,
                              @RequestParam("username") String username,
                              @RequestParam("password") String password) {
        System.out.println("username+password:" + username + password);
         UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        System.out.println("登录地址："+ getIp(request));
        Subject subject = SecurityUtils.getSubject();
        try {
            //登录操作
            subject.login(usernamePasswordToken);
            //  User user=(User) subject.getPrincipal();
            //更新用户登录时间，也可以在ShiroRealm里
            //  session.setAttribute("user", user);
            return new ResponseBean(200, "Login success", username + password);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (e instanceof IncorrectCredentialsException) {
                return new ResponseBean(201, "Login fail", "用户名或密码错误");
            }
            if (e instanceof LockedAccountException) {
                return new ResponseBean(201, "Login fail", "帐号已被锁定请联系管理员");
            }
        }
        return new ResponseBean(500, "server error", null);
    }

    /**
     * 创建日期:2018年4月6日<br/>
     * 代码创建:黄聪<br/>
     * 功能描述:通过request的方式来获取到json数据<br/>
     * @param jsonobject 这个是阿里的 fastjson对象
     * @return
     */

    @RequestMapping(value = "/login2", method = RequestMethod.POST)
    public ResponseBean getByJSON(@RequestBody Map o) {
        // 直接将json信息打印出来
        String name = (String) o.get("username");
        System.out.println(name);
        return new ResponseBean(200, "yes!!!", name);
    }





}
